<?php


if (!defined('RUN_FROM_INDEX')){
    die('Access Denied');
}

/* 模块的基本信息 */
if (isset($set_modules) && $set_modules == TRUE)
{
    $i = isset($modules) ? count($modules) : 0;
    $modules[$i]['name']    = 'paypalNVP';
    /* 代码 */
    $modules[$i]['code']    = basename(__FILE__, '.php');

    /* 描述对应的语言项 */
    $modules[$i]['desc']    = 'paypalNVP_desc';

    /* 是否支持货到付款 */
    $modules[$i]['is_cod']  = '0';

    /* 是否支持在线支付 */
    $modules[$i]['is_online']  = '1';

    /* 作者 */
    $modules[$i]['author']  = 'ECSHOP  TEAM';

    /* 网址 */
    $modules[$i]['website'] = 'http://www.paypal.com';

    /* 版本号 */
    $modules[$i]['version'] = '1.0.0';

    /* 配置信息 */

    	$modules[$i]['config'] = array(
	        array('name' => 'paypalNVP_username', 'label' =>'api用户名','type' => 'text', 'value' => ''),
			array('name' => 'paypalNVP_password', 'label' =>'api密码','type' => 'text', 'value' => ''),
			array('name' => 'paypalNVP_signature', 'label' =>'api签名','type' => 'text', 'value' => ''),
			array('name' => 'paypalNVP_version', 'label' =>'paypol版本','type' => 'text', 'value' => '54.0'),
			array('name' => 'paypalNVP_currency', 'label' =>'支付货币','type' => 'select', 'group' => array(0=>'USD'))
	    );
    return;
}

/**
 * 类
 */
class paypalNVP
{
	var $currencyCodeType;
	var $paymentType = 'Sale';
	var $returnURL;
	var $cancelURL;
    var $API_UserName;
	var $API_Password;
	var $API_Signature;
	//var $API_Endpoint = 'https://api-3t.paypal.com/nvp';
	var $API_Endpoint = 'https://api-3t.paypal.com/nvp';
	var $version = '54.0';
	
	var $use_Proxy = false;
	var $proxy_Host = '127.0.0.1';
	var $proxy_Port = '808';
	var $paypal_Url = 'https://www.paypal.com/cgi-bin/webscr&cmd=_express-checkout&token=';
    /**
     * 构造函数
     *
     * @access  public
     * @param
     *
     * @return void
     */
    function __construct()
    {
		include_once('./includes/lib_order.php');
		$sql = 'SELECT * FROM ' . $GLOBALS['ecs']->table('payment') .
            " WHERE pay_code = 'paypalNVP' AND enabled = 1";
		$payment = $GLOBALS['db']->getRow($sql);
		$payment = unserialize_config($payment['pay_config']);
		$this->API_UserName = $payment['paypalNVP_username'];
		$this->API_Password = $payment['paypalNVP_password'];
		$this->API_Signature = $payment['paypalNVP_signature'];
		$this->version = $payment['paypalNVP_version'];
		$this->currencyCodeType = isset($_SESSION['currency'])? $_SESSION['currency']: $payment['paypalNVP_currency'];
    }

//	function setExpressCheckout($nvpstr,$paypal)
//	{
//		$url=$GLOBALS['ecs']->url();
//		$returnURL =urlencode($url)."paypal.php?act=checkout";
//		$cancelURL =urlencode($url);
//		if($paypal){
//			$bn="&BUTTONSOURCE= PPCNMKT_2010_USPROMO";
//		}
//		return $resArray=$this->hash_call("SetExpressCheckout",$nvpstr."&PAYMENTACTION=".$this->paymentType."&ReturnUrl=".$returnURL."&CANCELURL=".$cancelURL ."&CURRENCYCODE=".$this->currencyCodeType.$bn);
//	}

	//mod hj 20110414 payapl活动(australia)
	function setExpressCheckout($nvpstr,$paypal,$sess="")
	{
		$url=$GLOBALS['ecs']->url();
		$returnURL =urlencode($url)."paypal.php?act=checkout";
		$cancelURL =urlencode($url)."flow.php";
		if($paypal){
			$bn="&BUTTONSOURCE= PPCNMKT_2010_USPROMO";
		}
	/*设置logo图片和颜色 du添加*/
	$logoimg = urlencode('https://www.lovelywholesale.com/pictures/paypal_lg.gif');
	$borderColor = '308ADA';	
		return $resArray=$this->hash_call("SetExpressCheckout",$nvpstr."&PAYMENTACTION=".$this->paymentType."&ReturnUrl=".$returnURL."&CANCELURL=".$cancelURL ."&CURRENCYCODE=".$this->currencyCodeType.$bn."&HDRIMG=".$logoimg."&PAYFLOWCOLOR=".$borderColor);
	}
	
	function getExpressCheckoutDetails($nvpstr)
	{
		   return $this->hash_call("GetExpressCheckoutDetails",$nvpstr);
	}
	
	function doExpressCheckoutPayment($nvpstr)
	{
		$nvpstr .= '&PAYMENTACTION='.urlencode($this->paymentType).'&CURRENCYCODE='.urlencode($this->currencyCodeType).'&IPADDRESS='.urlencode($_SERVER['SERVER_NAME']); 
		return $this->hash_call("DoExpressCheckoutPayment",$nvpstr);
	}
	
	function hash_call($methodName,$nvpStr)
	{
		//setting the curl parameters.
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,$this->API_Endpoint);
		curl_setopt($ch, CURLOPT_VERBOSE, 1);
	
		//turning off the server and peer verification(TrustManager Concept).
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
	
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
		curl_setopt($ch, CURLOPT_POST, 1);
		//if USE_PROXY constant set to TRUE in Constants.php, then only proxy will be enabled.
	   //Set proxy name to PROXY_HOST and port number to PROXY_PORT in constants.php 
		if($this->use_Proxy)
		curl_setopt ($ch, CURLOPT_PROXY, $this->proxy_Host.":".$this->proxy_Port); 
	
		//NVPRequest for submitting to server
		$nvpreq="METHOD=".urlencode($methodName)."&VERSION=".urlencode($this->version)."&PWD=".urlencode($this->API_Password)."&USER=".urlencode($this->API_UserName).'&LOCALECODE=US'."&SIGNATURE=".urlencode($this->API_Signature).$nvpStr;

		//setting the nvpreq as POST FIELD to curl
		curl_setopt($ch,CURLOPT_POSTFIELDS,$nvpreq);
	
		//getting response from server
		$response = curl_exec($ch);
	
		//convrting NVPResponse to an Associative Array
		$nvpResArray=$this->deformatNVP($response);
		$nvpReqArray=$this->deformatNVP($nvpreq);
		$_SESSION['nvpReqArray']=$nvpReqArray;
	
		if (curl_errno($ch)) {
			// moving to display page to display curl errors
			  $_SESSION['curl_error_no']=curl_errno($ch) ;
			  $_SESSION['curl_error_msg']=curl_error($ch);
			  $this->show_error();
		 } else {
			 //closing the curl
				curl_close($ch);
		  }
	
		return $nvpResArray;
	}
	
	/** This function will take NVPString and convert it to an Associative Array and it will decode the response.
	  * It is usefull to search for a particular key and displaying arrays.
	  * @nvpstr is NVPString.
	  * @nvpArray is Associative Array.
	  */
	function deformatNVP($nvpstr)
	{
	
		$intial=0;
		$nvpArray = array();
	
	
		while(strlen($nvpstr)){
			//postion of Key
			$keypos= strpos($nvpstr,'=');
			//position of value
			$valuepos = strpos($nvpstr,'&') ? strpos($nvpstr,'&'): strlen($nvpstr);
	
			/*getting the Key and Value values and storing in a Associative Array*/
			$keyval=substr($nvpstr,$intial,$keypos);
			$valval=substr($nvpstr,$keypos+1,$valuepos-$keypos-1);
			//decoding the respose
			$nvpArray[urldecode($keyval)] =urldecode( $valval);
			$nvpstr=substr($nvpstr,$valuepos+1,strlen($nvpstr));
		 }
		return $nvpArray;
	}
	
    /**
     * 生成支付代码
     * @param   array   $order  订单信息
     * @param   array   $payment    支付方式信息
     */
    function get_code($order, $payment)
    {
		$sql="select value from  who_shop_config where code='$_SESSION[currency]'";
		$rate=$GLOBALS['db']->getOne($sql);
        $data_order_id   = $order['order_id'];
		//$data_order_amount   = $order['order_amount']*$rate;
		$data_order_amount   = $order['order_amount'];
        $def_url  = '<br /><form style="text-align:center;" action="'. $GLOBALS['ecs']->url().'paypal.php" method="post">' .
            "<input type='hidden' name='act' value='checkout'>" .                      
            "<input type='hidden' name='order_id' value='$data_order_id'>" .
			"<input type='hidden' name='order_amount' value='$data_order_amount'>" .
            "<input type='submit' value='" . $GLOBALS['_LANG']['paypalNVP_button'] . "'>" .    // 按钮
            "</form><br />";

        return $def_url;
    }
	 function respond()
	 {
		 return true;
	 }
	
	function show_error()
	{
		$error_msg = '';
		$resArray=$_SESSION['reshash']; 
		if(isset($_SESSION['curl_error_no'])) { 
			$errorCode= $_SESSION['curl_error_no'] ;
			$errorMessage=$_SESSION['curl_error_msg'] ;	
			session_unset();
			$error_msg .= 'Error Number:'.$errorCode.'<br/>';
			$error_msg .= 'Error Message:'.$errorMessage.'<br/>';
			$error_msg .= 'Ack:'.$resArray['ACK'].'<br/>';
			$error_msg .= 'Correlation ID:'.$resArray['CORRELATIONID'].'<br/>';
			$error_msg .= 'Version:'.$resArray['VERSION'].'<br/>';
		}else{
			$count=0;
			while (isset($resArray["L_SHORTMESSAGE".$count])) {		
				  $errorCode    = $resArray["L_ERRORCODE".$count];
				  $shortMessage = $resArray["L_SHORTMESSAGE".$count];
				  $longMessage  = $resArray["L_LONGMESSAGE".$count]; 
				  $count=$count+1; 
				  $error_msg .= 'Error Number:'.$errorCode.'<br/>';
				  $error_msg .= 'Short Message:'.$shortMessage.'<br/>';
				  $error_msg .= 'Long Message:'.$longMessage.'<br/>';
			}
		}
		show_message($error_msg);
	}
}

?>